//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    class OleLink : IOfficeXmlSerializable
    {
        List<OleItem> _oleItems = new List<OleItem>();
        private string _progId;
        private Uri targetUri;

        #region IOfficeXmlSerializable Members

        public void ReadXml(ReadContext context)
        {
            using (var c = context.Read("oleLink"))
            {
                _progId = c.GetString("progId");
                string id = c.GetOptionalString(OfficeConstants.RelationshipNamespace + "id");
                var rel = c.Part.GetRelationship(id);
                this.targetUri = rel.TargetUri;

                _oleItems.Clear();
                _oleItems.AddRange(c.ReadElements<OleItem>("oleItems", "oleItem"));
                
            }

        }

        public void WriteXml(WriteContext context)
        {
            using (var c = context.Write("oleLink"))
            {
                c.SetString("progId", _progId);
                var rel = c.Part.CreateRelationship(targetUri, TargetMode.External, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject");
                c.SetString(OfficeConstants.RelationshipNamespace + "id", rel.Id);
                if (_oleItems.Count > 0)
                {
                    using (var c2 =c.Write("oleItems"))
                    {
                        c2.WriteElements(_oleItems);
                    }
                }
            }

        }

        #endregion
    }
}
